<template>
    <div class="app">
        <div class="nav">
            <Navi />
        </div>
        <div class="title">
            <span class="font">
                <p class="font-p">Show Your Message</p>
            </span>
        </div>
        <div class="user-info">
            <div class="user-info-l">
                <el-card class="box-card card1">
                    <div class="head">
                        <img @click="logout" class="avatar" :src="img" alt="Image">
                        
                    </div>
                    <div class="infos">
                        <el-upload
                            class="upload-demo"
                            action="http://127.0.0.1:8080/upload"
                            :data = {username}
                            :on-success="handleSuccess"
                            :disabled = !islogin
                            list-type="picture"
                        >
                            <el-button type="primary">点击我上传头像</el-button>
                        </el-upload>
                        <div>
                            欢迎您
                        </div>
                        <div style="font-size: 20px;color:#70b6fe;font-weight: bold;margin-top: 20px;">
                            {{ username }}
                        </div>
                    </div>
                </el-card>
            </div>
            <div class="user-info-r">
                <el-card class="box-card card2">
                    <div class="title_">
                        信息修改
                    </div>
                    <div class="information">
                        <el-input class="input-t" v-model="username" placeholder="请输入用户名"></el-input>
                        <el-input class="input-t" v-model="email" placeholder="请输入邮箱"></el-input>
                    </div>
                    <div class="title_">
                        密码修改
                    </div>
                    <div class="information">
                        <el-input class="input-t" type="password" v-model="password" placeholder="请输入密码"></el-input>
                        <el-input class="input-t" type="password" v-model="password" placeholder="请再次输入密码"></el-input>
                    </div>
                    <el-button class="submit" type="primary" @click="submit">确认</el-button>
                </el-card>
            </div>
        </div>
        <div>
            <BottomNavict />
        </div>
    </div>
</template>

<script setup>
import Navi from '@/components/Navict.vue'
import BottomNavict from './BottomNavict.vue'
import { ref } from 'vue'
//引入钩子函数
import { onMounted } from 'vue'
//引入axios进行请求发送
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
// 从vue-router导入useRouter，这是获取路由对象的方法  
import { useRouter } from 'vue-router';  


//获取路由对象
const router = useRouter();

//数据
const islogin = ref(false)
let username = ref('访客用户')
let password = ref('')
let password2 = ref('')
let email = ref('')
let img = ref('https://img.zcool.cn/community/01a6095f110b9fa8012066219b67d4.png?x-oss-process=image/auto-orient,1/resize,m_lfit,w_1280,limit_1/sharpen,100')

function base64ToBlobUrl(base64String, mimeType = "application/octet-stream") {
  // 将 Base64 字符串解码为二进制数据
  const binaryData = Uint8Array.from(atob(base64String), c => c.charCodeAt(0));

  // 创建 Blob 对象
  const blob = new Blob([binaryData], { type: mimeType });

  // 通过 URL.createObjectURL 创建 Blob 的 URL
  const blobUrl = URL.createObjectURL(blob);

  return blobUrl;
}


//获取用户信息
function getUserInfo(name){
    //发送请求
    axios.get("http://localhost:8080/getuser",{
        params:{
            username: name,
        }
    }).then(res => {
        if(res.data.code == 200){
            let user = res.data.result
            //赋值
            username.value = user.username
            email.value = user.email
            password.value = user.password
            password2.value = user.password
            img.value = base64ToBlobUrl(user.img)
            //存入sessionStorage
            sessionStorage.setItem('id',user.id)
        }
    })
}


function submit(){
    if(password.value != password2.value){
        alert('两次密码不一致')
        return
    }else{
        //发送请求
        axios.post("http://localhost:8080/updateUser",{
            //请求参数
            id: sessionStorage.getItem('id'),
            username: username.value,
            email: email.value,
            password: password.value

        },{
            //请求头
            headers: {
                //请求体
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' 
            }
        }).then(res => {
            if(res.data.code == 200){
                //修改session中的用户名
                sessionStorage.setItem('token',username.value)
                ElMessage.success('修改成功')
                //刷新页面
                window.location.reload()
            }else{
                ElMessage.error(res.data.msg)
            }
        })
    }
}

onMounted(() => {
    //设置用户状态
    //从session中获取用户信息
    const token = sessionStorage.getItem('token')
    if(token){
        username.value = token
        islogin.value = true
        console.log(islogin.value)
    }
    getUserInfo(username.value)

})

function logout(){
    if(islogin){
        ElMessageBox.confirm(
            '你将要退出登录，你确定继续吗?',
            'Warning',
            {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
            center: true,
            }
        )
            .then(() => {
            sessionStorage.removeItem('token');
            sessionStorage.removeItem('id');
            // 显示成功消息，注销成功
            ElMessage({
                type: 'success',
                message: '注销成功',
            })
            // 跳转到登录页面
            router.push('/login')
            })
            .catch(() => {
            // 显示信息消息，取消注销
            ElMessage({
                type: 'info',
                message: '取消注销',
            })
        })
    }else{
        router.push('/login')
    }
}

function handleSuccess(response, file, fileList){
    // 上传成功后执行的操作
    ElMessage({
        message:"上传成功",
        type:"success"
    })
    location.reload();
    
}
</script>

<style scoped>
    
    .app{
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
    }
    .title{
        width: 80%;
        height: 20%;
        margin: 0 auto;
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
    .font{
        width: 100%;
        font-size: 40px;
        color: #70b6fe;
        letter-spacing: 6px;
        font-weight: 600;
        text-transform: uppercase;
        display: flex;
        justify-content: center;
    }
    .font-p{
        width: 70%;
        text-align: center;
    }
    .user-info{
        width: 60%;
        height: auto;
        margin: 0 auto;
        margin-top: 20px;
        margin-bottom: 20px;
        display: flex;
        justify-content: space-evenly;
    }
    .user-info-l{
        width: 30%;
        height: auto;
    }
    .user-info-r{
        width: 70%;
        
    }
    .box-card{
        width: 100%;
        height: 100%;
        border-radius: 10px;
    }
    .card2{
        margin: 0 auto;
    }
    .title_{
        width: 90%;
        margin: 0 auto;
        margin: 10px 0;
        font-size: 20px;
    }
    .information{
        width: 90%;
        margin: 0 auto;
        padding: 10px;
    }
    .input-t{
        width: 100%;
        margin: 10px 0;
    }
    .submit{
        width: 87%;
        margin-left: 5%;
        margin-top: 20px;
    }
    .head{
        width: 100%;
        display: flex;
        justify-content: center;
    }
    
    .avatar{
        width: 100px;
        height: 100px;
        border-radius: 50%;
        margin: 0 auto;
        margin-top: 20px;
    }
    .infos{
        width: 100%;
        height: 100px;
        text-align: center;
    }
    .upload-demo{
        height: 150px;
        margin-top: 10px;
    }
</style>